/*
 * Copyright (c) 2007-2008, Thomas Krause (tho.krause@gmail.com)
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of gidoo nor the names of its contributors may be used to
 *       endorse or promote products derived from this software without specific
 *       prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.gidoo.cms.helper;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import org.apache.wicket.util.resource.AbstractResourceStreamWriter;
import org.apache.wicket.util.time.Time;
import org.gidoo.cms.GidooCMS;

/**
 * Streams a resource.
 * @author <a href="mailto:tho.krause@gmail.com>Thomas Krause</a>
 */
public class CMSResourceStreamWriter extends AbstractResourceStreamWriter
{
  
  private InputStream dataIn;
  private String mime;
  private long lastModified;
  private long size;
  
  /**
   * Constructor.
   * @param resource The resource to stream.
   * @param app The GidooCMS WebApplication.
   */
  public CMSResourceStreamWriter(Node resource, GidooCMS app)
  {
    if(resource == null || app == null)
    {
      throw new NullPointerException();
    }
    
    try
    {
      if(! "cms:resource".equals(resource.getPrimaryNodeType().getName()))
      {
        throw new IllegalArgumentException("resource param node needs to be of type \"cms:resource\"");
      }

      dataIn = resource.getProperty("jcr:data").getStream();
      mime = resource.getProperty("jcr:mimeType").getString();
      if(resource.hasProperty("jcr:lastModified"))
      {
        lastModified = resource.getProperty("jcr:lastModified").getDate().getTimeInMillis();
      }
      else
      {
        lastModified = new Date().getTime();
      }
      if(resource.hasProperty("cms:size"))
      {
        size = resource.getProperty("cms:size").getLong();
      }
      else
      {
        size = -1;
      }
    }
    catch(RepositoryException ex)
    {
      Logger.getAnonymousLogger().log(Level.SEVERE, "could not read resource stream", ex);
    }
  }

  public String getContentType()
  {
    return mime;
  }

  @Override
  public long length()
  {
    return this.size;
  }

  @Override
  public Time lastModifiedTime()
  {
    return Time.valueOf(lastModified);
  }

  public void write(OutputStream output)
  {
    if(dataIn != null)
    {
      try
      {
        BufferedInputStream in = new BufferedInputStream(dataIn);
        int b = in.read();
        while(b > -1)
        {
          output.write(b);
          b = in.read();
        }
        in.close();
      }
      catch (IOException ex)
      {
        Logger.getLogger(CMSResourceStreamWriter.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
}
